package com.sms.api.util;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class NewUtils {

    /**
     * 图片和视频 URL 的格式化
     *
     * @param url
     * @return
     */
    public static Object fixUrl(Object url) {
        if (url instanceof List) {
            return ((List) url).stream().map(NewUtils::fixUrl).collect(Collectors.toList());
        }
        String urlStr = (String) url;
        if (urlStr.startsWith("http:")) return urlStr;
        if (urlStr.startsWith("/")) return "http://touhao.oss-ap-southeast-1.aliyuncs.com" + urlStr;
        return url.toString();
    }

    public static void fixUrl(Map<String, Object> map, String key) {
        if (!map.containsKey(key)) return;
        map.compute(key, (k, v) -> fixUrl(v));
    }

    /**
     * 前端时间戳格式化为Long型
     *
     * @param time
     * @return
     */
    public static Long fixTimestamp(Object time) {
        if (time instanceof Long) return (Long) time;
        return Long.valueOf(time.toString());
    }

    public static void fixTimestamp(Map<String, Object> map, String key) {
        if (!map.containsKey(key)) return;
        map.compute(key, (k, v) -> fixTimestamp(v));
    }

    /**
     * 时间戳 转换成时间字符串
     *
     * @param
     */
    public static String longToStr(Long time) {
        if (StringUtil.isEmpty(time)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date(time));
    }
    public static String longToStrSecond(Long time) {
        if (StringUtil.isEmpty(time)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(time));
    }
    /**
     * 读取json对象
     * @param pactFile
     * @return
     * @throws IOException
     */
    public static String readJsonData(String pactFile){
        // 读取文件数据
        //System.out.println("读取文件数据util");

        StringBuffer strbuffer = new StringBuffer();
        File myFile = new File(pactFile);//"D:"+File.separatorChar+"DStores.json"
        if (!myFile.exists()) {
            System.err.println("Can't Find " + pactFile);
        }
        try {
            FileInputStream fis = new FileInputStream(pactFile);
            InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
            BufferedReader in  = new BufferedReader(inputStreamReader);

            String str;
            while ((str = in.readLine()) != null) {
                strbuffer.append(str);  //new String(str,"UTF-8")
            }
            in.close();
        } catch (IOException e) {
            e.getStackTrace();
        }
        //System.out.println("读取文件结束util");
        return strbuffer.toString();
    }

    /**
     * 获取请求ip
     * @param request
     * @return
     */

    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //Proxy-Client-IP：apache 服务代理
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //X-Real-IP：nginx服务代理
            ip = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ip != null && ip.length() != 0) {
            ip = ip.split(",")[0];
        }


        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }
}
